package com.atguigu.gulimall.product.web;

import cn.hutool.core.util.IdUtil;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author : Jungle
 * @Description : 前端的页面用controller
 */
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //System.out.println(Thread.currentThread().getId());
        // TODO: 1.查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevelCategorys();
        //默认的前缀和后缀
        // DEFAULT_PREFIX = "classpath:/templates/";
        // DEFAULT_SUFFIX = ".html";
        //视图解析器进行拼串。
        //cLasspath : /tempLates/ +返回值+.htmL
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    //index/json/catalog.json
    //这里需要返回json数据
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    //返回json 压测简单服务
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1.获取一把锁，只要锁名字一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁,是一个阻塞式等待，默认等待时间是30s
        //lock.lock();
        //1.锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s。不用担心业务时间长，锁自动过期被删掉
        //2.加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，默认在30秒以后自动删除
        //10秒后自动解锁  ，自动解锁时间一定要大于业务执行时间

        lock.lock(30, TimeUnit.SECONDS);
        //问题： lock.lock(10,TimeUnit.SECONDS)，在时间到了以后，不会再自动续期
        //1.如果我们传递了锁的超时时间，就发送redis执行脚本，进行占锁，默认就是我们指定的时间
        //2.如果我们未指定超时时间，就使用30 * 1000【LockWatchdogTimeout看门狗默认时间】
        //只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的默认时间】
        //internalLockLeaseTime【看门狗时间】 / 3，10s

        //最佳实战
        //lock.lock(10,TimeUnit.SECONDS); 省掉了整个续期操作，手动解锁
        try {
            System.out.println("加锁成功，执行业务" + Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(30);

        } catch (Exception e) {

        } finally {
            //3.解锁  将设解锁代码没有运行，redisson会不会出现死锁
            System.out.println("释放锁。。。" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 读写锁保证一定能读到最新数据，修改期间是一个排他锁（互斥锁，独享锁）。读锁是共享锁
     * 写锁没释放，读锁就必须等待
     * //读+读：相当于无锁  并发读，只会在redis中记录好，所有当前的读锁。他们都会同时加锁成功
     * //写＋读:等待写锁释放
     * //写+写:阻塞方式
     * //读+写: 有读锁，写也需要等待
     * //只要有写存在就必须等待
     */
    @ResponseBody
    @GetMapping("/write")
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            System.out.println("写锁加锁成功。。。" + Thread.currentThread().getId());
            //1、该数据加写锁，读数据加读锁
            s = IdUtil.fastSimpleUUID();
            TimeUnit.SECONDS.sleep(30);
            //放入redis
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("写锁释放成功。。。" + Thread.currentThread().getId());
            rLock.unlock();
        }
        return s;
    }


    @ResponseBody
    @GetMapping("/read")
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        //ReentrantReadWriteLock writeLock = new ReentrantReadWriteLock();
        String s = "";
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        System.out.println("读锁加锁成功。。。" + Thread.currentThread().getId());
        try {
            //取出redis
            s = redisTemplate.opsForValue().get("writeValue");
            TimeUnit.SECONDS.sleep(30);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("读锁释放成功。。。" + Thread.currentThread().getId());
            rLock.unlock();
        }
        return s;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量可以做分布式限流
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire(); //获取一个信号值，占用一个车位，阻塞式等待
        //尝试获取，获取不到返回false
        boolean b = park.tryAcquire();
        if (b) {
            //执行业务

        }else {
            return "error";
        }
        return "ok=>"+b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();  //释放一个停车位
        //Semaphore semaphore = new Semaphore(5);
        //semaphore.acquire();  //来一个车
        //semaphore.release();  //走一个车
        return "ok";
    }
    /**
     * 放假、锁门
     * 5个班全部走完可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id + "班的人都走了";
    }


}
